<template>
  <div class="orders">
    <h2>我的订单</h2>
    
    <!-- 购物车待支付订单 -->
    <div v-if="pendingCartItems.length > 0" class="pending-orders-section">
      <h3>待支付项目</h3>
      <el-table :data="pendingCartItems" style="width: 100%; margin-bottom: 20px;">
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="title" label="演出名称" />
        <el-table-column prop="date" label="演出时间" width="150" />
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="createOrder(scope.row)">创建订单</el-button>
            <el-button type="danger" size="small" @click="removeFromCart(scope.row.id)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 已创建的订单 -->
    <div v-if="orders.length > 0">
      <h3>已创建的订单</h3>
      <el-table :data="orders" style="width: 100%">
        <el-table-column prop="id" label="订单号" width="180" />
        <el-table-column prop="event.title" label="演出名称" />
        <el-table-column prop="event.date" label="演出时间" width="150" />
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="total_amount" label="总价" width="100">
          <template #default="scope">
            ¥{{ scope.row.total_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.status === 'pending'" type="primary" size="small" @click="payOrder(scope.row.id)">支付</el-button>
            <el-button v-if="scope.row.status === 'pending'" type="danger" size="small" @click="cancelOrder(scope.row.id)">取消订单</el-button>
            <el-button v-else size="small" disabled>{{ scope.row.status === 'paid' ? '已支付' : '已取消' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 空状态提示 -->
    <div v-if="orders.length === 0 && pendingCartItems.length === 0" class="empty-state">
      <el-empty description="暂无订单或待支付项目" />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import api from '../api'
import { useAppStore } from '../store'

export default {
  name: 'Orders',
  setup() {
    const store = useAppStore()
    const orders = ref([])

    // 计算属性：获取购物车中的待支付项目
    const pendingCartItems = computed(() => store.cart)

    // 获取已创建的订单
    const fetchOrders = async () => {
      try {
        const response = await api.get('/orders')
        orders.value = response
      } catch (error) {
        console.error('Failed to fetch orders:', error)
        // 错误信息不显示，避免影响用户体验
      }
    }

    // 从购物车移除项目
    const removeFromCart = (eventId) => {
      store.removeFromCart(eventId)
      ElMessage.success('已从购物车移除')
    }

    // 创建订单
    const createOrder = async (event) => {
      try {
        // 调用后端API创建订单
        const response = await api.post('/orders', {
          event_id: event.id,
          quantity: 1
        })
        
        // 从购物车中移除该项目
        store.removeFromCart(event.id)
        
        ElMessage.success('订单创建成功！')
        // 重新获取订单列表
        fetchOrders()
      } catch (error) {
        console.error('Failed to create order:', error)
        ElMessage.error('订单创建失败')
      }
    }

    // 支付订单
    const payOrder = async (orderId) => {
      try {
        await api.put(`/orders/${orderId}`, {
          status: 'paid'
        })
        ElMessage.success('支付成功！')
        // 重新获取订单列表
        fetchOrders()
      } catch (error) {
        console.error('Failed to pay order:', error)
        ElMessage.error('支付失败')
      }
    }

    // 取消订单
    const cancelOrder = async (orderId) => {
      try {
        await api.put(`/orders/${orderId}`, {
          status: 'cancelled'
        })
        ElMessage.success('订单已取消')
        // 重新获取订单列表
        fetchOrders()
      } catch (error) {
        console.error('Failed to cancel order:', error)
        ElMessage.error('取消订单失败')
      }
    }

    // 获取状态标签类型
    const getStatusType = (status) => {
      switch (status) {
        case 'paid': return 'success'
        case 'pending': return 'warning'
        case 'cancelled': return 'danger'
        default: return 'info'
      }
    }

    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'paid': return '已支付'
        case 'pending': return '待支付'
        case 'cancelled': return '已取消'
        default: return status
      }
    }

    // 组件挂载时获取订单列表
    onMounted(() => {
      fetchOrders()
    })

    return {
      orders,
      pendingCartItems,
      payOrder,
      cancelOrder,
      createOrder,
      removeFromCart,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.pending-orders-section {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 30px;
  background-color: #fafafa;
}

.empty-state {
  padding: 50px 0;
}
</style>